import { create } from "zustand";
import type { StateCreator } from "zustand";
import { immer } from "zustand/middleware/immer";
import {
  devtools,
  persist,
  subscribeWithSelector,
  createJSONStorage,
} from "zustand/middleware";
import { createSelectors } from "@/utils/createSelectors";
import { http } from "@/constant/status";
import { ServerGetMenuList, ServerGetLoginRecord } from "@go/app/ServerApp";
import { GetAllWindows } from "@go/app/App";

/** ---------------state start--------------- */
const initState = {
  sideTab: "/index", // 侧边栏tab
  isLogin: false, // 是否登录
  token: "", // token
  appLoading: false, // 应用加载中
  userInfo: {} as any, // 用户信息
  initApp: false, // 是否初始化应用信息
  appInfo: {
    version: "1.0",
  } as any, // 应用信息
  sideList: [] as any[], // 侧边栏列表
  loginRecordList: [] as any[], // 登录记录列表
  categoryList: [] as any[], // 分类列表
  currentCategory: undefined, // 当前分类
  currentHwnd: undefined as number | undefined, // 当前窗口句柄
  hwndList: [] as any[], // 窗口句柄列表
  currentCoordObj: { x: 0, y: 0, z: 0 } as any, // 当前坐标

  hotkeyModalVisible: false, // 热键模态框
  hotkeyModalInfo: {
    id: 0,
    hotkey: "",
  },
  settingModalVisible: false, // 设置弹框
};
/** ---------------state end--------------- */

/** ---------------方法start--------------- */

export const changeSideTab = (sideTab: string) => {
  useMainStore.setState({ sideTab });
};

export const initGlobal = async () => {
  getSideList();
};

// 获取侧边栏列表
export const getSideList = async () => {
  const res = await ServerGetMenuList();
  console.log("getSideList", res);
  if (res.code === http.StatusOK) {
    useMainStore.setState({ sideList: res.data });
  }
};

// 获取登录记录
export const getLoginRecord = async (token: string) => {
  const res = await ServerGetLoginRecord(token);
  if (res.code === http.StatusOK) {
    useMainStore.setState({ loginRecordList: res.data });
  }
};

export const getHwndList = async () => {
  const res1 = await GetAllWindows("", "七日世界");
  const res2 = await GetAllWindows("", "[#] 七日世界 [#]");
  const hwndList1 = (res1.data || [])
    .filter((item: any) => item.name)
    .map((item: any) => ({
      label: item.name,
      value: item.hwnd,
    }));
  const hwndList2 = (res2.data || [])
    .filter((item: any) => item.name)
    .map((item: any) => ({
      label: item.name,
      value: item.hwnd,
    }));
  const allList = [...hwndList1, ...hwndList2];
  console.log("hwndList", allList);
  // 如果在allList中找不到currentHwnd，则清空currentHwnd
  if (
    !allList.find((item) => item.value === useMainStore.getState().currentHwnd)
  ) {
    useMainStore.setState({ currentHwnd: undefined });
  }
  useMainStore.setState({ hwndList: allList });
};

/** ---------------方法end--------------- */

const createMainSlice: StateCreator<
  typeof initState,
  [
    ["zustand/immer", never],
    ["zustand/devtools", unknown],
    ["zustand/subscribeWithSelector", never],
    ["zustand/persist", unknown]
  ]
> = () => initState;

export const useMainStore = createSelectors(
  create<typeof initState>()(
    immer(
      devtools(
        subscribeWithSelector(
          persist(createMainSlice, {
            // 存储名称(必须唯一)
            name: "mainStore",
            // 自定义存储(默认localStorage)
            storage: createJSONStorage(() => sessionStorage),
            // 只存储某个字段
            // partialize: (state) => ({ bears: state.bears, color: state.color }),
            // 不存储某个字段
            // partialize: (state) =>
            //   Object.fromEntries(
            //     Object.entries(state).filter(
            //       ([key]) =>
            //         !["currentHwnd"].includes(
            //           key
            //         )
            //     )
            //   ),
          })
        ),
        {
          enabled: true, // 是否启用devtools
          name: "mainStore", // devtools名称
        }
      )
    )
  )
);
